<template>
<div id="Lv3_discuss">
    
    <!-- <div id="navi" style="line-height: 5vh;color: #ffffff;">
        <el-link :underline="false"><el-icon size="20px" color="#ffffff"><ArrowLeftBold /></el-icon></el-link>
        讨论
    </div> -->
    <div class="search">
        <div class="fil">
            <span class="fil-title">讨论</span>
            <ElInput v-model="search" style="width:210px;margin-right: 30px;" placeholder="搜索"></ElInput>
            <el-button @click="publicTalks = true">全部讨论</el-button>
            <el-button @click="publicTalks = false">我发布的</el-button>
        </div>
        <div class="btns">
            <el-button plain type="primary" icon="plus" style="height: 40px;width:40px;" @click="newTalk"></el-button>
        </div>
    </div>

    <div style="height:calc(100% - 60px);" :style="{position:'relative'}" >
        <div class="discuss-list">
        <div class="discuss-item" v-for="(talk,index) in theTalks" :key="talk._id">
            <div class="left">
                <div class="portrait">
                    <ElImage style="height: 50px;width:50px;" class="avatar" fit="cover" :src="conf.server +  talk.user.portrait"></ElImage>
                </div>
            </div>
            
            <div class="right">
                <div class="context">
                    <div class="text">
                        <span class="name">{{ talk.user.name }}&nbsp;:&nbsp;</span>{{ talk.context }}
                    </div>
                </div>
                <div class="photos" v-if="talk.photos">
                    <div class="pic"  v-for="(photo,index) in talk.photos" :key="photo" >
                        <ElImage @click="picClicked(photo)" lazy style="height: 100px;width:100px" fit="cover" :src="conf.server + photo">
                            <template #placeholder>
                                <div class="image-slot">Loading<span class="dot">...</span></div>
                            </template>
                        </ElImage>
                    </div>
                </div>
                <div class="controls">
                    <div class="time">{{ talk.time.format('yyyy-MM-dd hh:mm:ss') }}</div>
                    <div class="btns">
                        <ElButton type="primary" link size="small" @click="followTalk(talk)">评论</ElButton>
                        <ElButton type="primary" link size="small" @click="deleteTalk(talk._id)" v-if="talk.user._id === currentUser._id">删除</ElButton>
                    </div>
                </div>

                <div class="follow" v-if="talk.follows.length !== 0">
                    <div class="discuss-item" v-for="follow in talk.follows" :key="follow._id">
                        <div class="left">
                            <div class="portrait">
                                <ElImage style="height: 50px;width:50px;" class="avatar" fit="cover" :src="conf.server +  follow.user.portrait"></ElImage>
                            </div>
                        </div>
                        <div class="right">
                            <div class="context">
                                <div class="text">
                                    <span class="name">{{ follow.user.name }}&nbsp;:&nbsp;</span>{{ follow.context }}
                                </div>
                            </div>
                            <div class="photos" v-if="follow.photos">
                                <div class="pic"  v-for="(photo,index) in follow.photos" :key="photo" >
                                    <ElImage @click="picClicked(photo)" lazy style="height: 100px;width:100px" fit="cover" :src="conf.server + photo">
                                        <template #placeholder>
                                            <div class="image-slot">Loading<span class="dot">...</span></div>
                                        </template>
                                    </ElImage>
                                </div>
                            </div>

                            <div class="controls">
                                <div class="time">{{ follow.time.format('yyyy-MM-dd hh:mm:ss') }}</div>
                                <div class="btns">
                                    <ElButton type="primary" link size="small"  @click="deleteFollowTalk(talk._id,follow._id)" v-if="follow.user._id === currentUser._id">删除</ElButton>
                                    <!-- <ElButton type="primary" link size="small" @click="deleteTalk(talk._id)" v-if="talk.user._id === currentUser._id">删除</ElButton> -->
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- <div class="follows">
                    <div v-for="follow in talk.follows" :key="follow._id">
                    {{ follow }}
                    <div class="follow-control">
                        <ElButton @click="deleteFollowTalk(talk._id,follow._id)" v-if="follow.user._id === currentUser._id">删除</ElButton>
                    </div>
                    </div>
                </div> -->
            </div>
        </div>
     
    </div>
    </div>

    <el-dialog
        v-model="dialogVisible"
        title="发布讨论"
        width="40%"
        :close-on-click-modal="false"
        :show-close="false"
        custom-class="dialog"
    >
        <ElForm>
            <ElFormItem prop="context" >
                <ElInput v-model="context" type="textarea" :rows="6"></ElInput>
            </ElFormItem>
            <ElFormItem >
                <el-upload
                    v-model:file-list="fileList"
                    class="upload-demo"
                    action="#"
                    multiple
                    :before-remove="beforeRemove"
                    :limit="10"
                    :on-exceed="handleExceed"
                    :http-request="async () => {}"
                    accept=".jpg,.png"
                >
                    <el-button type="primary">点击上传图片</el-button>
                </el-upload>
            </ElFormItem>
        </ElForm>
        <template #footer>
        <span class="dialog-footer">
            <el-button @click="cancel">取消</el-button>
            <el-button type="primary" @click="upload"> 发表 </el-button>
        </span>
        </template>
    </el-dialog>

</div>
</template>



<script lang="ts" setup>
import { onMounted, ref, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { storeToRefs } from 'pinia';
import { useClientStore } from '../pinia/stores/client';
import { talks } from '../shared/types/talks';
import { UploadProps,UploadUserFile } from 'element-plus'
import { conf } from '@/utils/conf';

const route = useRoute()
const router = useRouter()
const courseId = route.params.courseId as string
const { currentCourseId,currentUser,client } = storeToRefs(useClientStore())

const publicTalks = ref(true)
const talks = ref<talks[]>()
const search = ref('')
const theTalks = computed(() =>{
    const reg = new RegExp(search.value)
    if(publicTalks.value){
        return talks.value?.filter(t => reg.test(t.context) || reg.test(t.user.name))
    }
    else{
        return talks.value?.filter(talk => talk.user._id === currentUser.value._id && (reg.test(talk.context) || reg.test(talk.user.name)))
    }
})

const mode = ref<'new' | 'follow'>('new')
const mianTalk = ref<talks>()
const dialogVisible = ref(false)
const context = ref('')
const fileList = ref<UploadUserFile[]>([]);
const fileDatas = new Array<{
  fileName: string;
  fileData: Uint8Array;
  fileType: string;
}>();
const newTalk = () =>{
    mode.value = 'new'
    dialogVisible.value = true
}
const followTalk = (talkId:talks) =>{
    mode.value = 'follow'
    mianTalk.value = talkId
    dialogVisible.value = true
}
const handleExceed = () => {
  ElMessage.warning("最多一次性上传10个文件");
};
const beforeRemove: UploadProps["beforeRemove"] = (uploadFile, uploadFiles) => {
  return ElMessageBox.confirm(`确定移除 ${uploadFile.name} 吗?`).then(
    () => true,
    () => false
  );
};
const cancel = () => {
  fileList.value.length = 0;
  fileDatas.length = 0;
  dialogVisible.value = false;
  context.value = ''
};
const upload = async () =>{
    loadingInstance = ElLoading.service({
        target:'.dialog'
    })
    if(!context.value){
        ElMessage.warning('请输入内容')
        loadingInstance.close()
        return
    }

    try {
        const pros = fileList.value.map(async (file) => {
        if (file.raw) {
            fileDatas.push({
            fileName: file.raw.name,
            fileType: file.raw.type,
            fileData: new Uint8Array(await file.raw.arrayBuffer()),
            });
            return;
        }
        });
        await Promise.all(pros);
    } catch (error) {
        loadingInstance.close()
        if(error instanceof Error) ElMessage.error(error.message)
    }

    if(mode.value === 'new'){
        const ret = await client.value.callApi('talks/NewTalks',{
            course:courseId,
            context:context.value,
            photos:fileDatas.length === 0?undefined:fileDatas
        })
        if(ret.isSucc){
            talks.value?.unshift(ret.res.talk)
            ElMessage.success('发布成功')
        }
    }
    else{
        const ret = await client.value.callApi('talks/FollowTalks',{
            context:context.value,
            photos:fileDatas.length === 0?undefined:fileDatas,
            mainTalk:mianTalk.value?._id as string
        })
        if(ret.isSucc){
            mianTalk.value?.follows.unshift(ret.res.followTalk)
            mianTalk.value = undefined
        }
    }
    loadingInstance.close()
    cancel()
}

const deleteTalk =async (talkId:string) =>{
    try {
        await ElMessageBox.confirm('确定要删除评论吗')
        loadingInstance = ElLoading.service({
            target:'#app'
        })
        const ret = await client.value.callApi('talks/DeleteTalk',{
            talkId
        })
        if(ret.isSucc){
            const ret = await client.value.callApi('talks/GetTalks',{
                type:'public',
                course:courseId
            })
            if(ret.isSucc){
                talks.value = ret.res.talks
                ElMessage.success('删除成功')
            }
        }
        loadingInstance.close()
    } catch (error) {
        console.log(error);
    }
}
const deleteFollowTalk = async (talkId:string,followTalkId:string) =>{
    try {
        await ElMessageBox.confirm('确定要删除评论吗')
        loadingInstance = ElLoading.service({
            target:'#app'
        })
        const ret = await client.value.callApi('talks/DeleteFollowTalk',{
            talkId,
            followTalkId
        })
        if(ret.isSucc){
            const ret = await client.value.callApi('talks/GetTalks',{
                type:'public',
                course:courseId
            })
            if(ret.isSucc){
                talks.value = ret.res.talks
                ElMessage.success('删除成功')
            }
        }
        loadingInstance.close()
    } catch (error) {
        console.log(error);
    }
}

const picClicked = (url:string) =>{
    self.open(`/#/file?url=${url}&name=picture`)
}

let loadingInstance:any
onMounted(async () =>{
    loadingInstance = ElLoading.service({
        target:'#app'
    })
    if(!courseId){
        ElMessage.error('不存在')
        loadingInstance.close()
        router.back()
        return
    }
    currentCourseId.value = courseId

    const ret = await client.value.callApi('talks/GetTalks',{
        type:'public',
        course:courseId
    })
    if(ret.isSucc){
        talks.value = ret.res.talks
    }


    loadingInstance.close()
})
</script>

<style lang="less" scoped>
#Lv3_discuss{
    word-wrap: break-word;
    overflow: auto;
    height: calc(100% + 60px);
    width: 100%;
    .search{
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
        padding-right: 50px;
        background-color: #f2f8ff48;
        display: flex;
        align-items: center;
        justify-content: space-between;
        .fil{
            display: flex;
            align-items: center;
            .fil-title{
                font-size: 20px;
                font-weight: bold;
                color: #909292b5;
                margin-right: 20px;
            }
        }
    }
}

.discuss-list{
    height: calc(100% - 60px);
    width: 100%;
    padding: 0px 10px;
    overflow: auto;
    .discuss-item{
        position: relative;
        // height: 150px;
        width: 100%;
        background-color: #f2f8ff47;
        border-radius: 10px;
        margin: 10px 0;
        // cursor: pointer;
        display: flex;
        
        &:nth-of-type(2n){
            background-color: #f2f8ff26;
        }
        &:hover{
            // background-color: #f2f8ff9c;
        }
        .left{
            display: flex;
            width: 120px;
            justify-content: center;
            padding: 20px 0;
            .portrait{
                margin-left: 20px;
                border-radius: 50%;
                overflow: hidden;
                height: 50px;
                width: 50px;
            }
        }
        .right{
            // width: 94%;
            width: calc(100% - 120px);
            padding: 20px;
            padding-left: 0px;
            padding-right: 80px;
            display: flex;
            flex-direction: column;
            font-size: 14px;
            & > div{
                width: 100%;
                margin-bottom: 5px;
            }
            .context{
                .text{
                    line-height: 25px;
                    .name{
                        color: #478ace;
                    }
                }
            }
            .photos{
                display: flex;
                flex-wrap: wrap;
                .pic{
                    border: 1px solid rgba(0, 0, 0, 0);
                    position: relative;
                    z-index: 1;
                    transition: transform 0.2s;
                    cursor: pointer;
                    &:hover{
                        transform: scale(1.2);
                        z-index: 2;
                    }
                    .image-slot{
                        line-height: 100px;
                        text-align: center;
                    }
                }
            }
            .controls{
                margin-bottom:0;
                line-height: 25px;
                display: flex;
                justify-content: space-between;
                .time{
                    font-size: 12px;
                    color: #a0a0a0eb;
                }
                .btns{
                    float: right;
                    height: 25px;
                    
                }
            }
            .follow{
                // height: 100px;
                background-color: #f3f3f33d;
                
                border-radius: 10px;
            }
        }
    }
}

// .disscuss{
//     margin: 20px 0px 20px 0px;
//     width: 100%;
//     height: 300px;
//     border-radius: 5px;
//     background-color: rgb(235, 80, 80);
//     padding: 0 10px;
//     padding-top: 20px;
//     .mainDis{
//         background-color: rgb(255, 255, 255);
//         position: relative;
//         width: 100%;
//         border-radius: 5px;
//     }
//     .avatar{
//         width: 50px;
//         height: 50px;
//         border-radius: 5px;
//         background-image: url('../public/icon.png');
//         background-size: 100%;
//         position: relative;
//         top: 10px;
//         left: 10px;
//     }

//     .id{
//         // position: relative;
//         // left: 70px;
//         // top: -40px;
//     }
    
//     .el-badge{
//         margin-right:30px;
//     }
//     .time{
//         position: relative;
//         // left: 1140px;
//     }
// }
</style>